package com.zjsru.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.zjsru.feign.OrderFeignClient;
import com.zjsru.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;
    
    @Autowired
    private OrderFeignClient orderFeignClient;

    @GetMapping("/execute")
    public String executePayment(@RequestParam Long orderId, @RequestParam Long userId) {
        try {
            // 从订单服务获取订单详情
            OrderFeignClient.OrderDetail orderDetail = orderFeignClient.getOrderDetail(orderId);
            if (orderDetail == null) {
                return "支付失败：无法获取订单信息";
            }
            
            // 调用 PaymentService 处理支付逻辑
            Long paymentId = paymentService.executePayment(orderId, orderDetail.getUserId(), orderDetail.getTotalAmount());
            return "支付成功，支付流水ID：" + paymentId;
        } catch (Exception e) {
            return "支付失败：" + e.getMessage();
        }
    }

    // 您可以保留或修改现有的 /info/{username} 接口，或者删除
    // @SentinelResource(value = "paymentInfo", blockHandler = "paymentBlockException",fallback = "paymentFallback")
    // @GetMapping("/info/{username}")
    // public String paymentInfo(@PathVariable("username") String username) {
    //     //算需要支付多少钱，这里模拟一下
    //     return "恭喜你"+username+"支付成功了";
    // }
    // /*blockHandler*/
    // public String paymentBlockException(String s, Throwable e) {
    //     return "异常信息：" + e.getMessage();
    //
    // }
    // /*fallback*/
    // public String paymentFallback(String s) {
    //     return "排队人数过多，请稍等";
    // }
    // //添加流控
    // @PostConstruct
    // private void initFlowRules(){
    //    List<FlowRule> rules = new ArrayList<>();
    //    FlowRule rule = new FlowRule();
    //    rule.setResource("paymentInfo");
    //    rule.setGrade(1);
    //    rule.setCount(1);
    //    rules.add(rule);
    //    FlowRuleManager.loadRules(rules);
    // }
}
